from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from utils import preprocess_email
import nltk

# 在应用启动时下载必要的NLTK资源
try:
    nltk.download('stopwords', quiet=True)
    nltk.download('punkt', quiet=True)
except Exception as e:
    print(f"NLTK资源下载失败: {str(e)}")

app = Flask(__name__)
# 防止中文乱码
app.config['JSON_AS_ASCII'] = False

# MySQL 配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost:3306/emails'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


# 定义数据表
class Email(db.Model):
    __tablename__ = 'email'
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text)
    category = db.Column(db.String(50))
    status = db.Column(db.String(20))
    isdeleted = db.Column(db.Boolean, default=False)


# 跨域的处理
CORS(app)


# 插入数据前先查询，主键是id不可重复添加
def judge_data_is_exist(email_id):
    single_record = db.session.query(Email).filter_by(id=email_id).first()
    return bool(single_record)


# 数据库数据全查询
def query_emails_info(message="", status="", filter_status=None, page=1, page_size=10):
    """
    查询邮件信息
    参数:
        message: 返回消息
        status: 返回状态
        filter_status: 过滤的状态值(可选)
        page: 当前页码(默认1)
        page_size: 每页数量(默认10)
    """
    result_info = {'status': status}
    response_object = []
    try:
        # 确保page和page_size是整数
        page = int(page)
        page_size = int(page_size)
        
        print(f"当前请求页码: {page}, 每页数量: {page_size}")
        
        # 构建查询条件
        query = db.session.query(Email)
        
        # 计算总数
        total = query.count()
        print(f"总记录数: {total}")
        
        # 计算偏移量
        offset = (page - 1) * page_size
        print(f"计算的偏移量: {offset}")
        
        # 执行分页查询
        paginated_emails = query.order_by(Email.id).offset(offset).limit(page_size).all()
        print(f"查询到的记录数: {len(paginated_emails)}")
        
        # 处理数据
        for email in paginated_emails:
            # 对邮件内容进行预处理
            try:
                processed_content = preprocess_email(email.content) if email.content else ""
            except Exception as e:
                print(f"预处理邮件内容失败: {str(e)}")
                processed_content = email.content  # 如果预处理失败，使用原始内容
            
            email_dict = {
                'id': email.id,
                'content': email.content,
                'processed_content': processed_content,  # 使用预处理后的内容
                'category': email.category,
                'status': email.status,
                'isdeleted': email.isdeleted
            }
            response_object.append(email_dict)

        result_info.update({
            'total': total,
            'message': message or "查询成功",
            'status': "success",
            'current_page': page,
            'page_size': page_size,
            'emails': response_object
        })
        
        print(f"返回数据: 总数={total}, 当前页={page}, 每页数量={page_size}, 记录数={len(response_object)}")
        
    except Exception as e:
        print(f"查询出错: {str(e)}")
        result_info.update({
            'message': f"查询失败: {str(e)}",
            'status': "error",
            'emails': []
        })
    return result_info


@app.route('/selectEmailList', methods=['GET', 'POST'])
def all_emails():
    # 查询所有邮件
    if request.method == 'GET':
        try:
            # 从请求参数中获取分页信息并转换为整数
            page = int(request.args.get('page', 1))
            page_size = int(request.args.get('pageSize', 10))
            
            print(f"接收到的分页参数: page={page}, pageSize={page_size}")  # 调试日志
            
            result_info = query_emails_info(
                message="获取邮件列表成功", 
                status="success",
                page=page,
                page_size=page_size
            )
            return jsonify(result_info)
        except ValueError as e:
            return jsonify({
                'status': 'error',
                'message': '分页参数格式错误',
                'emails': []
            })
        except Exception as e:
            return jsonify({
                'status': 'error',
                'message': f'查询失败: {str(e)}',
                'emails': []
            })

    # # 添加新邮件
    # if request.method == 'POST':
    #     try:
    #         json_data = request.get_json()
    #
    #         new_email = Email(
    #             content=json_data.get('content'),
    #             category=json_data.get('category'),
    #             status=json_data.get('status'),
    #             isdeleted=json_data.get('isdeleted', False)
    #         )
    #
    #         db.session.add(new_email)
    #         db.session.commit()
    #
    #         result_info = query_emails_info("邮件添加成功!", "success")
    #         return jsonify(result_info)
    #     except Exception as e:
    #         db.session.rollback()
    #         return jsonify({
    #             'status': 'error',
    #             'message': f'添加邮件失败: {str(e)}',
    #             'emails': []
    #         })


@app.route('/update_email/<int:email_id>', methods=['PUT', 'DELETE'])
def update_email(email_id):
    # if request.method == "PUT":
    #     json_data = request.get_json()
    #     db.session.query(Email).filter(Email.id == email_id).update(json_data)
    #     db.session.commit()
    #     result_info = query_emails_info("邮件更新成功!", "success")
    #     return jsonify(result_info)

    if request.method == 'DELETE':
        try:
            # 将 isdeleted 字段更新为 True，而不是物理删除记录
            db.session.query(Email).filter_by(id=email_id).update({"isdeleted": True})
            db.session.commit()
            result_info = query_emails_info("邮件删除成功!", "success")
            return jsonify(result_info)
        except Exception as e:
            db.session.rollback()
            return jsonify({
                'status': 'error',
                'message': f'删除邮件失败: {str(e)}',
                'emails': []
            })


# 添加新的路由处理status=0的查询
@app.route('/pending_emails', methods=['GET'])
def get_pending_emails():
    """获取所有status为0的待处理邮件"""
    result_info = query_emails_info("获取垃圾邮件成功", "success", filter_status="0")
    return jsonify(result_info)


if __name__ == "__main__":
    with app.app_context():
        db.create_all()
    app.run(host="0.0.0.0", debug=True)
